import axios from "axios";
import { _apiUrl, timeOut } from './axiosConfig'
import { Toast } from "vant";
import router from '@/router'
const localStorageKey = import.meta.env.VITE_APP_TOKEN || null
export const http = axios.create({
    timeout: timeOut,
    baseURL: _apiUrl
})
// 请求拦截
http.interceptors.request.use(config => {
    config.headers['authorization'] = localStorage.getItem(localStorageKey)
    return config
}, (error) => {
    return Promise.reject(error)
})

//响应拦截
// code 表 
/* 
   302 重定向登录
   401 账号不存在
   402 账号已被注册
   403 密码错误
   404 页面丢失
   202 需要进一步传输 image
*/

const codeList = [401, 402, 403, 404]

http.interceptors.response.use(response => {
    // todo 
    if (codeList.indexOf(response.data.code) !== -1) {
        Toast.fail({
            message: response.data.msg
        })
        return Promise.reject(response.data.msg)
    }
    if (response.data.code === 302) {
        localStorage.removeItem(import.meta.env.VITE_APP_USERMSG)
        localStorage.removeItem(import.meta.env.VITE_APP_TOKEN)
        Toast(response.data.msg)
        setTimeout(router.push({ path: '/user' }), 1000)
    }
    return response
}, (error) => {
    if (error.toString().slice(39) == '401') {
        Toast('账号不存在')
        return Promise.reject(error)
    }
    if (error.toString().slice(39) == '403') {
        Toast('密码错误')
        return Promise.reject(error)
    }
    if (error.toString().slice(39) == '402') {
        Toast('账号已注册')
        return Promise.reject(error)
    }
    Toast(error.toString())
    return Promise.reject(error)
})